﻿
using Core.SimpleTemp.Application;
using Core.SimpleTemp.Common;
using Core.SimpleTemp.Common.Authorization;
//using Core.SimpleTemp.Common.Core.Repository.Internal.Data;
using Core.SimpleTemp.Common.PagingQuery;
using Core.SimpleTemp.Entitys;
using Core.SimpleTemp.Mvc.Api.Internal;
using Core.SimpleTemp.Repositories.Internal;
using Core.Toolkit.Authorization;
using Core.Toolkit.Core;
using Core.Toolkit.Core.Api;
using Core.Toolkit.Core.Application;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace Core.SimpleTemp.Api.Api.YH
{
    /// <summary>
    /// 隐患等级
    /// </summary>
    [ApiExplorerSettings(GroupName = "YH")]//swagger分类标签
    [Route("api/[controller]")]//路由说明
    [EnableCors("any")]//跨域规则
    [ApiController]//APi标识Controller
    [Authorize]
    public class YH_GradeController : CoreApiController
    {
        private readonly YH_GradeService _service;
        private readonly CoreDBContext _dbContext;
        /// <summary>
        /// YH_Grade
        ///</summary>
        public YH_GradeController(YH_GradeService service, CoreDBContext dbContext)
        {
            _service = service;
            _dbContext = dbContext;
        }

        #region 基础增删改查
        /// <summary>
        /// 查询
        ///</summary>
        /// <param name="pagingQueryModel"></param>
        /// <returns></returns>
        [HttpPost("GetList")]
        [PermissionFilter(nameof(YH_GradeController) + "_" + nameof(YH_GradeController.GetList), AuthorizationConst.LIST)]
        public async Task<IActionResult> GetList(PagingModel<YH_GradeDto> pagingQueryModel)
        {
            var result = await _service.GetList(pagingQueryModel);
            result.PageData.ForEach(a =>
            {
                string res = "";
                a.YH_GradePost.ToList().ForEach(b =>
                {
                    if (!b.IsDeleted)
                        res += "[" + b.PostName + "],";
                });
                res = res.Length > 0 ? res.Substring(0, res.Length - 1) : res;
                a.PostNames = res;
            });
            return this.JsonSuccess(result);
        }

        /// <summary>
        /// 添加/修改
        ///</summary>
        /// <param name="dto"></param>
        /// <returns></returns>

        [HttpPost("Save")]
        [PermissionFilter(nameof(YH_GradeController) + "_" + nameof(YH_GradeController.SaveAsync), AuthorizationConst.SAVE)]
        public async Task<IActionResult> SaveAsync(YH_GradeDto dto)
        {
            var entity=new YH_GradeDto();
            dto.YH_GradePost = null;
            await KeepOnlyOneMajor(dto, _dbContext);
            //添加
            if (Equals(dto.Id, Guid.Empty))
            {
                dto.CreateFactory = UserIdentity.Factory;
                entity = await _service.InsertAsync(dto);
            }
            else
            {
                entity = await _service.UpdateAsync(dto);
            }
            if (entity.Id != null)
            {
                await _dbContext.SaveChangesAsync();
            }
            return this.JsonSuccess(string.Empty);
        }
        /// <summary>
        /// 保持永远只有一个等级为重大等级
        /// </summary>
        private async Task KeepOnlyOneMajor(YH_GradeDto dto, CoreDBContext _db)
        {
            if (dto.IsMajor)
            {
                var list = await _db.Set<YH_Grade>().Where(x => x.IsDeleted == false && x.IsMajor == true).ToListAsync();
                for (int i = 0; i < list.Count; i++)
                {
                    list[i].IsMajor = false;
                }

            }
        }

        /// <summary>
        /// DeleteMuti
        ///</summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("DeleteMuti")]
        [PermissionFilter(nameof(YH_GradeController) + "_" + nameof(YH_GradeController.DeleteMutiAsync), AuthorizationConst.DELETE)]
        public async Task<IActionResult> DeleteMutiAsync([FromBody]Guid[] ids)
        {

            await _service.DeleteBatchAsync(ids);
            return this.JsonSuccess();

        }


        /// <summary>
        /// 根据ID获取信息
        ///</summary>
        /// <param name="id"></param>
        /// <returns></returns>

        [HttpGet("Get")]
        [PermissionFilter(nameof(YH_GradeController) + "_" + nameof(YH_GradeController.Get), AuthorizationConst.GET)]
        public async Task<IActionResult> Get(Guid id)
        {
            var model = await _service.GetForPCAsync(id);
            model.YH_GradePost = model.YH_GradePost.Where(a => a.IsDeleted == false).ToList();
            return this.JsonSuccess(model);
        }
        #endregion

        /// <summary>
        /// 修改通知职务
        ///</summary>
        /// <param name="dtos"></param>
        /// <returns></returns>
        [HttpPost("UpdateGradePost")]
        [PermissionFilter(nameof(YH_GradeController) + "_" + nameof(YH_GradeController.UpdateGradePostAsync), "保存隐患等级通知岗位")]
        public async Task<IActionResult> UpdateGradePostAsync(UpdateLevelDutyModel dtos)
        {
            List<YH_GradePostDto> list = new List<YH_GradePostDto>();
            foreach (var item in dtos.SysDutyIDs)
            {
                list.Add(new YH_GradePostDto
                {
                    PostId = item,
                    GradeId = dtos.GradeId
                });
            }
            await _service.UpdateGradePostAsync(dtos.GradeId, list);
            return this.JsonSuccess();
        }
        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost("Import")]
        [PermissionFilter(nameof(YH_GradeController) + "_" + "导入")]
        public async Task<IActionResult> ImportAsync([FromForm]List<IFormFile> file)
        {
            var retMeg = await _service.ImportAsync(file[0]);
            if (!retMeg.Any())
                return this.JsonSuccess();
            else
                return this.JsonFaild(null, retMeg);
        }
        /// <summary>
        /// 导出
        ///</summary>
        /// <param name="pagingQueryModel"></param>
        /// <returns></returns>

        [HttpPost("Export")]
        [PermissionFilter(nameof(YH_GradeController) + "_" + nameof(YH_GradeController.Export), AuthorizationConst.EXPORT)]
        public async Task<IActionResult>
            Export(PagingModel<YH_GradeDto>
                pagingQueryModel)
        {
            var fileName = await _service.Export(pagingQueryModel);
            if (string.IsNullOrWhiteSpace(fileName))
                return this.JsonFaild(NULL_DATA_FOR_EXCEL_EXPORT);
            return this.JsonSuccess(fileName);
        }
    }
    /// <summary>
    /// 
    /// </summary>
    public class UpdateLevelDutyModel
    {
        /// <summary>
        /// 
        /// </summary>
        [Required]
        public Guid GradeId { get; set; }
        /// <summary>
        /// 
        /// </summary>
        [Required]
        public Guid[] SysDutyIDs { get; set; }
    }
}
